package com.learn.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.learn.shop.constant.R;
import com.learn.shop.pojo.entriy.NovelChapterMongo;
import com.learn.shop.pojo.vo.PageVo;
import com.learn.shop.utils.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("details")
@Api(tags = "小说章节内容")
@Slf4j
public class NovelDetailsToMongo {

    private static final Logger logger = LoggerFactory.getLogger(NovelDetailsToMongo.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("list")
    @ApiOperation("详情")
    public R queryNovelDetails(@RequestBody @Validated PageVo pageVo) {
        int pageNum = pageVo.getPageNum();
        int pageSize = pageVo.getPageSize();
        Set<String> collectionNames = mongoTemplate.getCollectionNames();
        if (!collectionNames.contains(pageVo.getNovelName())) {
            return R.fail("不存在此小说!");
        }
        long count = mongoTemplate.getCollection(pageVo.getNovelName()).countDocuments();

        logger.info("集合的长度为:" + count);
        Query query = Query.query(Criteria.where("novelNo").gte(0))
                .with(Sort.by(Sort.Direction.ASC, "novelNo"))
                .skip(pageSize * (pageNum - 1))
                .limit(pageSize);
        List<NovelChapterMongo> list = mongoTemplate.find(query, NovelChapterMongo.class, pageVo.getNovelName());
        PageResult<List<NovelChapterMongo>> res = new PageResult<>();

        int pages = (int) (count / pageSize);
        res.setTotal((int) count);
        res.setData(list);
        res.setPageNum(pageNum);
        res.setPageSize(pageSize);
        res.setPages(pages);
        res.setSize(list.size());
        if (pageNum < 2) {
            res.setFirstPage(true);
        } else {
            res.setPrePage(pageNum - 1);
        }
        if (pageNum >= pages) {
            res.setLastPage(true);
        } else {
            res.setNextPage(pageNum + 1);
        }
        String resJson = JSONArray.toJSON(res).toString();
        logger.info("获取小说<<" + pageVo.getNovelName() + ">>的结果为:" + resJson);
//        System.out.println(resJson);

        return R.ok(res, "查询成功!");
    }
}
